Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add mutex and set a fixed number for ThreadPool #36

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

hebangwen
Copy link

std::chrono::system_clock::now().time_since_epoch() :获取从 1970 年开始到现在经过的时间,算作时间段,但是由于是从 0 开始的,所以也可以算作是时间点。

若运行策略等于 std::launch::async 且实现无法开始新线程(该情况下,若运行策略为 async|deferred 或设置了额外位,则它将回退到 deferred 或实现定义的策略),则抛出以 std::errc::resource_unavailable_try_again 为错误条件的 std::system_error,或者若无法分配内部数据结构所用的内存,则为 std::bad_alloc

bad_alloc:说明无法分配内存。system_error:无法创建新线程。

线程池里用 thread 实现,即

struct ThreadPool {
    std::vector<std::future<void>> futures;
    std::vector<std::thread> threads;

    void create(std::function<void()> start) {
        futures.push_back(std::async(std::launch::async, start));
        // threads.push_back(std::thread {start});
    }

    ~ThreadPool() {
        for (auto &ftr: futures) ftr.wait();
        for (auto &thread: threads) thread.join();
    }
};

std::launch::async 和 std::thread 是一样的,都是创建之后就马上开始运行子线程。但是这样并不能把 262144 * 3 个子线程全部执行完,当 i = 10830 的时候就报 system_error,无法创建新线程了;如果用 std::launch::deferred 惰性执行就没有问题,可以成功执行并且退出;如果不特意指定异步的启动方式,它可能是两者其中之一,但是也只能运行 24w 左右。

解决方案就是增加检测 vector 长度的代码,如果 vector 过长,则先等待 vector 中的线程或者协程执行完,才能增加新的线程。通过手动限制线程池的大小,避免了这个问题。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant